package com.csii.branch.controller;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.csii.branch.controller.vo.*;
import com.csii.core.system.vo.LoginUser;

import com.csii.core.api.Result;
import com.csii.core.system.query.QueryGenerator;
import com.csii.core.util.ConvertUtils;
import com.csii.core.util.oConvertUtils;
import com.csii.branch.mapper.entity.CdBranchLicenseInfo;
import com.csii.branch.service.dto.CdBranchLicenseInfoDTO;
import com.csii.branch.mapper.entity.CdBranchPlaceInfo;
import com.csii.branch.service.dto.CdBranchPlaceInfoDTO;
import com.csii.branch.mapper.entity.CdBranchDeviceInfo;
import com.csii.branch.service.dto.CdBranchDeviceInfoDTO;
import com.csii.branch.mapper.entity.CdBranchSupervisorInfo;
import com.csii.branch.service.dto.CdBranchSupervisorInfoDTO;
import com.csii.branch.mapper.entity.CdBranchAroundInfo;
import com.csii.branch.service.dto.CdBranchAroundInfoDTO;
import com.csii.branch.mapper.entity.CdBranchBaseInfo;
import com.csii.branch.service.dto.CdBranchBaseInfoDTO;
import com.csii.branch.service.ICdBranchBaseInfoService;
import com.csii.branch.service.ICdBranchLicenseInfoService;
import com.csii.branch.service.ICdBranchPlaceInfoService;
import com.csii.branch.service.ICdBranchDeviceInfoService;
import com.csii.branch.service.ICdBranchSupervisorInfoService;
import com.csii.branch.service.ICdBranchAroundInfoService;
import com.csii.autopoi.poi.excel.ExcelImportUtil;
import com.csii.autopoi.poi.excel.entity.ExportParams;
import com.csii.autopoi.poi.excel.entity.ImportParams;
import com.csii.autopoi.web.def.NormalExcelConstants;
import com.csii.autopoi.web.view.EntityExcelView;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.csii.core.annotation.AutoLog;

 /**
 * @Description: 网点基本信息
 * @Author: power-stdio
 * @Date:   2020-12-22
 * @Version: V1.0
 */
@Api(tags="网点基本信息")
@RestController
@RequestMapping("/cdBranchBaseInfo")
@Slf4j
public class CdBranchBaseInfoController {
	@Autowired
	private ICdBranchBaseInfoService cdBranchBaseInfoService;
	@Autowired
	private ICdBranchLicenseInfoService cdBranchLicenseInfoService;
	@Autowired
	private ICdBranchPlaceInfoService cdBranchPlaceInfoService;
	@Autowired
	private ICdBranchDeviceInfoService cdBranchDeviceInfoService;
	@Autowired
	private ICdBranchSupervisorInfoService cdBranchSupervisorInfoService;
	@Autowired
	private ICdBranchAroundInfoService cdBranchAroundInfoService;


	@ApiOperation(value="查询子网点基本信息列表")
	@GetMapping(value = "listByPid")
	public Result<List<BranchBaseVo>> listByPid(String pid) {
		List<CdBranchBaseInfo> list=cdBranchBaseInfoService.list(new LambdaQueryWrapper<CdBranchBaseInfo>().select(CdBranchBaseInfo::getId,CdBranchBaseInfo::getArea,CdBranchBaseInfo::getName,
				CdBranchBaseInfo::getLatitude,CdBranchBaseInfo::getLongitude,CdBranchBaseInfo::getNetLevel,CdBranchBaseInfo::getPid,CdBranchBaseInfo::getAear)
				.eq(CdBranchBaseInfo::getPid, StrUtil.isNotEmpty(pid)?pid:"0"));
		 return Result.ok(ConvertUtils.convertList(BranchBaseVo.class,list));
	 }
	/**
	 * 分页列表查询
	 *
	 * @param cdBranchBaseInfoVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "网点基本信息-分页列表查询")
	@ApiOperation(value="网点基本信息-分页列表查询", notes="网点基本信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CdBranchBaseInfoVO cdBranchBaseInfoVO,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		CdBranchBaseInfo cdBranchBaseInfo = ConvertUtils.convert(CdBranchBaseInfo.class,cdBranchBaseInfoVO);
		QueryWrapper<CdBranchBaseInfo> queryWrapper = QueryGenerator.initQueryWrapper(cdBranchBaseInfo, req.getParameterMap());
		Page<CdBranchBaseInfo> page = new Page<CdBranchBaseInfo>(pageNo, pageSize);
		IPage<CdBranchBaseInfo> pageList = cdBranchBaseInfoService.page(page, queryWrapper);
		IPage<CdBranchBaseInfoVO> pageListVo = ConvertUtils.convertIPage(CdBranchBaseInfoVO.class, pageList);
		return Result.ok(pageListVo);
	}
	
	/**
	 *   添加
	 *
	 * @param cdBranchBaseInfoVOPage
	 * @return
	 */
	@AutoLog(value = "网点基本信息-添加")
	@ApiOperation(value="网点基本信息-添加", notes="网点基本信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CdBranchBaseInfoVOPage cdBranchBaseInfoVOPage) {
		CdBranchBaseInfoDTO cdBranchBaseInfoDTO = ConvertUtils.convert(CdBranchBaseInfoDTO.class,cdBranchBaseInfoVOPage);
		cdBranchBaseInfoService.saveMain(cdBranchBaseInfoDTO, ConvertUtils.convertList(CdBranchLicenseInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchLicenseInfoVOList()),ConvertUtils.convertList(CdBranchPlaceInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchPlaceInfoVOList()),ConvertUtils.convertList(CdBranchDeviceInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchDeviceInfoVOList()),ConvertUtils.convertList(CdBranchSupervisorInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchSupervisorInfoVOList()),ConvertUtils.convertList(CdBranchAroundInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchAroundInfoVOList()));
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cdBranchBaseInfoVOPage
	 * @return
	 */
	@AutoLog(value = "网点基本信息-编辑")
	@ApiOperation(value="网点基本信息-编辑", notes="网点基本信息-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CdBranchBaseInfoVOPage cdBranchBaseInfoVOPage) {
		CdBranchBaseInfoDTO cdBranchBaseInfoDTO = ConvertUtils.convert(CdBranchBaseInfoDTO.class,cdBranchBaseInfoVOPage);
		CdBranchBaseInfo cdBranchBaseInfoEntity = cdBranchBaseInfoService.getById(cdBranchBaseInfoDTO.getId());
		if(cdBranchBaseInfoEntity==null) {
			return Result.error("未找到对应数据");
		}
		cdBranchBaseInfoService.updateMain(cdBranchBaseInfoDTO, ConvertUtils.convertList(CdBranchLicenseInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchLicenseInfoVOList()),ConvertUtils.convertList(CdBranchPlaceInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchPlaceInfoVOList()),ConvertUtils.convertList(CdBranchDeviceInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchDeviceInfoVOList()),ConvertUtils.convertList(CdBranchSupervisorInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchSupervisorInfoVOList()),ConvertUtils.convertList(CdBranchAroundInfoDTO.class, cdBranchBaseInfoVOPage.getCdBranchAroundInfoVOList()));
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网点基本信息-通过id删除")
	@ApiOperation(value="网点基本信息-通过id删除", notes="网点基本信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		cdBranchBaseInfoService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "网点基本信息-批量删除")
	@ApiOperation(value="网点基本信息-批量删除", notes="网点基本信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cdBranchBaseInfoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网点基本信息-通过id查询")
	@ApiOperation(value="网点基本信息-通过id查询", notes="网点基本信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CdBranchBaseInfo cdBranchBaseInfo = cdBranchBaseInfoService.getById(id);
		if(cdBranchBaseInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(cdBranchBaseInfo);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网点证照信息通过主表ID查询")
	@ApiOperation(value="网点证照信息主表ID查询", notes="网点证照信息-通主表ID查询")
	@GetMapping(value = "/queryCdBranchLicenseInfoByMainId")
	public Result<?> queryCdBranchLicenseInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CdBranchLicenseInfo> cdBranchLicenseInfoList = cdBranchLicenseInfoService.selectByMainId(id);
		return Result.ok(cdBranchLicenseInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网点房屋通过主表ID查询")
	@ApiOperation(value="网点房屋主表ID查询", notes="网点房屋-通主表ID查询")
	@GetMapping(value = "/queryCdBranchPlaceInfoByMainId")
	public Result<?> queryCdBranchPlaceInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CdBranchPlaceInfo> cdBranchPlaceInfoList = cdBranchPlaceInfoService.selectByMainId(id);
		return Result.ok(cdBranchPlaceInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网点设备信息通过主表ID查询")
	@ApiOperation(value="网点设备信息主表ID查询", notes="网点设备信息-通主表ID查询")
	@GetMapping(value = "/queryCdBranchDeviceInfoByMainId")
	public Result<?> queryCdBranchDeviceInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CdBranchDeviceInfo> cdBranchDeviceInfoList = cdBranchDeviceInfoService.selectByMainId(id);
		return Result.ok(cdBranchDeviceInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网点装修信息通过主表ID查询")
	@ApiOperation(value="网点装修信息主表ID查询", notes="网点装修信息-通主表ID查询")
	@GetMapping(value = "/queryCdBranchSupervisorInfoByMainId")
	public Result<?> queryCdBranchSupervisorInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CdBranchSupervisorInfo> cdBranchSupervisorInfoList = cdBranchSupervisorInfoService.selectByMainId(id);
		return Result.ok(cdBranchSupervisorInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网点周边信息通过主表ID查询")
	@ApiOperation(value="网点周边信息主表ID查询", notes="网点周边信息-通主表ID查询")
	@GetMapping(value = "/queryCdBranchAroundInfoByMainId")
	public Result<?> queryCdBranchAroundInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CdBranchAroundInfo> cdBranchAroundInfoList = cdBranchAroundInfoService.selectByMainId(id);
		return Result.ok(cdBranchAroundInfoList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cdBranchBaseInfo
    */
    @PostMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CdBranchBaseInfo cdBranchBaseInfo) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CdBranchBaseInfo> queryWrapper = QueryGenerator.initQueryWrapper(cdBranchBaseInfo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

      //Step.2 获取导出数据
      List<CdBranchBaseInfo> queryList = cdBranchBaseInfoService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<CdBranchBaseInfo> cdBranchBaseInfoList = new ArrayList<CdBranchBaseInfo>();
      if(oConvertUtils.isEmpty(selections)) {
          cdBranchBaseInfoList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          cdBranchBaseInfoList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<CdBranchBaseInfoVOPage> pageList = new ArrayList<CdBranchBaseInfoVOPage>();
      for (CdBranchBaseInfo main : cdBranchBaseInfoList) {
          CdBranchBaseInfoVOPage vo = ConvertUtils.convert(CdBranchBaseInfoVOPage.class,main);
          List<CdBranchLicenseInfo> cdBranchLicenseInfoList = cdBranchLicenseInfoService.selectByMainId(main.getId());
          vo.setCdBranchLicenseInfoVOList(ConvertUtils.convertList(CdBranchLicenseInfoVO.class, cdBranchLicenseInfoList));
          List<CdBranchPlaceInfo> cdBranchPlaceInfoList = cdBranchPlaceInfoService.selectByMainId(main.getId());
          vo.setCdBranchPlaceInfoVOList(ConvertUtils.convertList(CdBranchPlaceInfoVO.class, cdBranchPlaceInfoList));
          List<CdBranchDeviceInfo> cdBranchDeviceInfoList = cdBranchDeviceInfoService.selectByMainId(main.getId());
          vo.setCdBranchDeviceInfoVOList(ConvertUtils.convertList(CdBranchDeviceInfoVO.class, cdBranchDeviceInfoList));
          List<CdBranchSupervisorInfo> cdBranchSupervisorInfoList = cdBranchSupervisorInfoService.selectByMainId(main.getId());
          vo.setCdBranchSupervisorInfoVOList(ConvertUtils.convertList(CdBranchSupervisorInfoVO.class, cdBranchSupervisorInfoList));
          List<CdBranchAroundInfo> cdBranchAroundInfoList = cdBranchAroundInfoService.selectByMainId(main.getId());
          vo.setCdBranchAroundInfoVOList(ConvertUtils.convertList(CdBranchAroundInfoVO.class, cdBranchAroundInfoList));
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "网点基本信息列表");
      mv.addObject(NormalExcelConstants.CLASS, CdBranchBaseInfoVOPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("网点基本信息数据", "导出人:"+sysUser.getRealname(), "网点基本信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
		  InputStream isr = null;
		  try {
			  isr = file.getInputStream();
              List<CdBranchBaseInfoVOPage> list = ExcelImportUtil.importExcel(isr, CdBranchBaseInfoVOPage.class, params);
              for (CdBranchBaseInfoVOPage page : list) {
                  CdBranchBaseInfoDTO po = ConvertUtils.convert(CdBranchBaseInfoDTO.class,page);
                  cdBranchBaseInfoService.saveMain(po, ConvertUtils.convertList(CdBranchLicenseInfoDTO.class, page.getCdBranchLicenseInfoVOList()),ConvertUtils.convertList(CdBranchPlaceInfoDTO.class, page.getCdBranchPlaceInfoVOList()),ConvertUtils.convertList(CdBranchDeviceInfoDTO.class, page.getCdBranchDeviceInfoVOList()),ConvertUtils.convertList(CdBranchSupervisorInfoDTO.class, page.getCdBranchSupervisorInfoVOList()),ConvertUtils.convertList(CdBranchAroundInfoDTO.class, page.getCdBranchAroundInfoVOList()));
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
			  if (isr != null) {
				  try {
					  isr.close();
				  } catch (IOException e) {
					  e.printStackTrace();
				  }
			  }
		  }
      }
      return Result.ok("文件导入失败！");
    }

}
